package com.interceptor;

import com.common.ConstantUtil;
import com.common.JSONPObjectUtil;
import com.common.ThreadLocalVarUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CrossDomainInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*CORS 跨域访问允许*/
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("P3P", "CP=CAO PSA OUR");
        response.setCharacterEncoding(ConstantUtil.CHARSET_UTF8);
        /*JSONP callback参数获取*/
        String callback = request.getParameter(JSONPObjectUtil.CALL_BACK_PARAM_NAME);
        if (StringUtils.isNotBlank(callback)) {
            ThreadLocalVarUtil.put(JSONPObjectUtil.CALL_BACK_PARAM_NAME, callback);
        }
        return super.preHandle(request, response, handler);
    }

}